﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Top.Api;
using Top.Api.Request;

namespace Top.Module.Activities
{
    public sealed class TopActivity<T> : CodeActivity
            where T : TopResponse
    {
        public InArgument<string> ServerUrl { get; set; }
        public InArgument<string> AppKey { get; set; }
        public InArgument<string> AppSecret { get; set; }
        public InArgument<string> SessionKey { get; set; }

        public InArgument<ITopRequest<T>> Request { get; set; }
        public OutArgument<T> Response { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string serverUrl = context.GetValue(this.ServerUrl);
            string appKey = context.GetValue(this.AppKey);
            string appSecret = context.GetValue(this.AppSecret);
            string sessionKey = context.GetValue(this.SessionKey);
            var request = context.GetValue(this.Request);

            if (request != null && !String.IsNullOrEmpty(serverUrl) && !String.IsNullOrEmpty(appKey) && !String.IsNullOrEmpty(appSecret))
            {
                var response = default(T);

                ITopClient client = new DefaultTopClient(serverUrl, appKey, appSecret);
                response = client.Execute(request, sessionKey);
                if (response.IsError)
                {
                    throw new TopException(response.ErrCode, response.ErrMsg);
                }
                context.SetValue(this.Response, response);
            }
            else
            {
                throw new TopException("传入的参数未正确的初始化！");
            }
        }
    }
}
